#usr/bin/python

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
from gui import canvas, canvas_GL, canvas_spectrogram
from core import pySpec as obj
from controller import web_browser_control, BaseController as base
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import os.path as path

import matplotlib.pyplot as plt



	
class Dock_Control(base):
	"""
	class to handle events the main dock widget
	"""
	
	def __init__(self, win, lspl):
		"""
		constructor
		"""
		base.__init__(self, lspl, win)		
		
		#connection
		#plotting
		QtCore.QObject.connect(self.dialog.treeView, QtCore.SIGNAL("doubleClicked (const QModelIndex &)"),self.getSelection)
		
		#change spectr/chrom
		QtCore.QObject.connect( self.main_window.pushButton, QtCore.SIGNAL(" clicked () " ), self.main_window.updateTreeView )
		
		#plotting 
		QtCore.QObject.connect(self.main_window.treeView_2, QtCore.SIGNAL("doubleClicked (const QModelIndex &)"),self.peakSelection)
		QtCore.QObject.connect(self.dialog.treeView_3, QtCore.SIGNAL("doubleClicked (const QModelIndex &)"),self.peakSelection2)
		
		self.dialog.treeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) 
		self.dialog.treeView_2.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.dialog.treeView_3.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

		#show context menu in the different treeview
		QtCore.QObject.connect(self.dialog.treeView, QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), self.dialog.showCustomContextMenu)
		QtCore.QObject.connect(self.dialog.treeView_2, QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), self.dialog.showCustomContextMenu)
		QtCore.QObject.connect(self.dialog.treeView_3, QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), self.dialog.showCustomContextMenu)
		
		#connect actions of the context menu
		QtCore.QObject.connect(self.dialog.treeView_actions[0], QtCore.SIGNAL("triggered()"), self.EraseItem)
		QtCore.QObject.connect(self.dialog.treeView_actions[1], QtCore.SIGNAL("triggered()"), self.plot_multiple_selection)
		#QtCore.QObject.connect(self.dialog.treeView_actions[2], QtCore.SIGNAL("triggered()"), self.plot_corr)
		QtCore.QObject.connect(self.dialog.treeView_actions[3], QtCore.SIGNAL("triggered()"), self.show_3D)
		QtCore.QObject.connect(self.dialog.treeView_actions[5], QtCore.SIGNAL("triggered()"), self.show_cytoscape)
		QtCore.QObject.connect(self.dialog.treeView_actions[4], QtCore.SIGNAL("triggered()"), self.show_spectrogram)
	
	
	
	def template(self):
		"""
		return the xml_name of the treeview- to improve!!!
		#def template_bis(self, treeview, model)
		@xml_file
		"""
		for index in self.dialog.treeView.selectedIndexes():
			if index.isValid():
				xml_file = self.dialog.chrom_model.data(index.parent(), Qt.DisplayRole).toString()
				if xml_file != "":
					return xml_file
				else:
					del xml_file
					return self.dialog.chrom_model.data(index, Qt.DisplayRole).toString()				
			else:
				self.dialog.ShowErrorMessage("fatalError", "Error on an index...can not do anything... SORRY!")
				
		for index in self.dialog.treeView.selectedIndexes():
			if index.isValid():
				xml_file = self.dialog.spectr_model.data(index.parent(), Qt.DisplayRole).toString()
				if index.parent()!="":
					return xml_file
				else:
					del xml_file
					return self.dialog.spectr_model.data(index, Qt.DisplayRole).toString()
			else:
				self.dialog.ShowErrorMessage("fatalError", "Error on an index...can not do anything... SORRY!")
			
		for index in self.dialog.treeView_2.selectedIndexes():
			if index.isValid():
				xml_file = self.dialog.peak_model.data(index.parent(), Qt.DisplayRole).toString()
				if index.parent()!="":
					return xml_file
				else:
					del xml_file
					return self.dialog.peak_model.data(index, Qt.DisplayRole).toString()
			else:
				self.dialog.ShowErrorMessage("fatalError", "Error on an index...can not do anything... SORRY!")
		
		for index in self.dialog.treeView_3.selectedIndexes():
			if index.isValid():
				xml_file = self.dialog.clust_model.data(index.parent(), Qt.DisplayRole).toString()
				if index.parent() !="":
					return xml_file
				else:
					del xml_file
					return self.dialog.clust_model.data(index, Qt.DisplayRole).toString()
			else:
				self.dialog.ShowErrorMessage("fatalError", "Error on an index...can not do anything... SORRY!")
	
	
	
	
	def show_cytoscape(self):
		"""
		launch cytoscape
		"""
		self.dialog.ShowInStatusBar("Launching Cytoscape web. Please Wait...", 5000)
		xml_file =self.template()
		print "xmlfile 3D", xml_file

		web = web_browser_control.httpWidget(self.dialog)
		web.ui.tab_widget.currentWidget().webview.load(QtCore.QUrl(path.normcase("controller/test.html")))
		self.dialog.addMdiSubWindow(web, "Scatter plot of "+str(xml_file))
		
		
	def show_spectrogram(self):
		"""
		launch the scatter plot with the colormap
		"""
		self.dialog.ShowInStatusBar("Scatter plotting.Please Wait...", 10000)
		xml_file =self.template()
		self.dialog.addMdiSubWindow(canvas_spectrogram.Spectrogram(self.lspl.Sample(str(xml_file))).get_canvas(), "Scatter plot of "+str(xml_file))
		
	def show_3D(self):
		"""
		to show in 3D
		"""
		self.dialog.ShowInStatusBar("3D plotting.Please Wait...", 10000)
		xml_file =self.template()
		print "xmlfile 3D", xml_file
		self.dialog.addMdiSubWindow(canvas_GL.canvas_GL(self.lspl.Sample(str(xml_file))), "3D plot of "+str(xml_file))
		

	def getSelection(self, index):
		"""
		Allow to plot chrom and spectr
		"""
		
		xml_file = self.dialog.chrom_model.data(index).toString()
		if xml_file in self.lspl.getFiles():
			self.dialog.ShowInStatusBar("3D plotting.Please Wait...", 2000)
			wid =canvas_GL.canvas_GL(self.lspl.Sample(xml_file))#
			self.dialog.addMdiSubWindow(wid, xml_file)
			return
			
		if index.model() == self.dialog.chrom_model :
			xml_file = self.dialog.chrom_model.data(index.parent(), Qt.DisplayRole).toString()
			transition = float(self.dialog.chrom_model.data(index).toString().split('/')[0]) #just remove the float
			print transition
			self.dialog.addMdiSubWindow(self.lspl.SampleTrans(xml_file, transition).plot(),  "Chromatogram@"+str(transition)) 
			
		else:
			xml_file = self.dialog.spectr_model.data(index.parent(), Qt.DisplayRole).toString()
			time = self.dialog.spectr_model.data(index).toString()
			self.dialog.addMdiSubWindow(self.lspl.SampleSpectr(xml_file, time).plot(),  "Spectrum@"+str(time))
			
	def peakSelection(self, index):
		"""Allow to plot peak and peak tables"""
		
		xml_file = self.dialog.peak_model.data(index).toString()
		if xml_file in self.lspl.getFiles():
			view= QtGui.QTableView()
			view.setSortingEnabled(True)
			view.setModel(self.lspl.Sample(xml_file).get_peak_model())
			self.dialog.addMdiSubWindow(view,  "PeakList of"+ str(xml_file))
			return
			
		xml_file = self.dialog.peak_model.data(index.parent(), Qt.DisplayRole).toString()
		data = str(self.dialog.peak_model.data(index).toString()).split(" ")
		prec=float(data[0])
		rt = float(data[1])
		for peaks in self.lspl.Sample(xml_file).get_peak_list():
			if peaks.get_trans_prec() ==prec and peaks.get_rt() == rt:
				canvass =peaks.plot()
				control = canvas_peak_control.canvas_peak_control(self.lspl.Sample(xml_file),peaks, self.dialog.addMdiSubWindow(canvass,  "peak@ "+str(prec)+"/"+str(rt)), self.dialog)
				canvass.exec_()
				return
				
	def peakSelection2(self, index):
		"""Allow to plot peak and cluster tables"""
		
		xml_file = self.dialog.clust_model.data(index).toString()
		if xml_file in self.lspl.getFiles():
			view= QtGui.QTableView()
			view.setSortingEnabled(True)
			view.setModel(self.lspl.Sample(xml_file).get_clust_model())
			self.dialog.addMdiSubWindow(view,  "ClusterList of"+str(xml_file))
			return
		if self.dialog.clust_model.data(index.parent(), Qt.DisplayRole).toString()== "Fragments_adducts" or \
			self.dialog.clust_model.data(index.parent(), Qt.DisplayRole).toString()== "Isotopic_cluster":
				
			xml_file = self.dialog.clust_model.data(index.parent().parent().parent(), Qt.DisplayRole).toString()
		else:
			xml_file = self.dialog.clust_model.data(index.parent(), Qt.DisplayRole).toString()
			
		data = str(self.dialog.clust_model.data(index).toString()).split(" ")
		prec=float(data[0])
		rt = float(data[1])
		for peaks in self.lspl.Sample(xml_file).get_peak_list():
			if peaks.get_trans_prec() ==prec and peaks.get_rt() == rt:
				canvass =peaks.plot()
				control = canvas_peak_control.canvas_peak_control(self.lspl.Sample(xml_file),peaks, self.dialog.addMdiSubWindow(canvass,  "peak@ "+str(prec)+"/"+str(rt)), self.dialog)
				canvass.exec_()
				
		if self.dialog.clust_model.data(index.parent(), Qt.DisplayRole).toString()== "Fragments_adducts":
			data1 = str(self.dialog.clust_model.data(index).toString()).split(" ")
			data2 = str(self.dialog.clust_model.data(index.parent().parent()).toString()).split(" ")
			prec1=float(data1[0]);prec2 =float(data2[0])
			rt1 = float(data1[1]);rt2 =float(data2[1])
			parent =None; son =None
			for peaks in self.lspl.Sample(xml_file).get_peak_list():
				if peaks.get_trans_prec() ==prec1 and peaks.get_rt() == rt1:
					son =peaks
				elif peaks.get_trans_prec() ==prec2 and peaks.get_rt() == rt2:
					parent =peaks
			self.dialog.addMdiSubWindow(canvas.canvasUi([parent.get_Y_data()], [son.get_Y_data()], flags ="corr"),  "Correlation between "+str(parent.get_trans_prec()))
	
	def plot_multiple_selection(self):
		"""
		Plot several chromatograms in the same canvas
		"""
		
		list_mass =[]
		for index in self.dialog.treeView.selectedIndexes():
			xml_file = self.dialog.chrom_model.data(index.parent(), Qt.DisplayRole).toString()
			transition = float(self.dialog.chrom_model.data(index).toString().split('/')[0])
			list_mass.append((xml_file, transition))
		chromas =[];
		for item in list_mass:
			chromas.append(self.lspl.SampleTrans(item[0], item[1]))
		list_rt =[];list_intensity=[]
		for c in chromas:
			list_rt.append(c.rt)
			list_intensity.append(c.intensity)
		
		self.dialog.addMdiSubWindow(canvas.canvasUi(list_rt, list_intensity,\
				legends =tuple([str(item[1]).join(["chrom@",""]) for item in list_mass]), flags ="chrom"))
		

		
	def EraseItem(self):
		"""
		Erase One line in the treeView
		"""
		
		for index in self.dialog.treeView.selectedIndexes():
		#if not index.parent():
			if index.isValid():
					#print "remove root..."
					#i.e we are on one root of the tree name file
				value = self.dialog.ShowWarningMessage("Remove Data", "Remove selected Index will lead to the loss of information")
				if value == QtGui.QMessageBox.Cancel:
					return
				index_data = self.dialog.chrom_model.data(index, Qt.DisplayRole).toString()
				
				#remove the row in the model
				self.dialog.chrom_model.removeRow(index.row())
				self.dialog.spectr_model.removeRow(index.row())
				#update the view
				self.dialog.treeView.rowsRemoved(index, index.row(), index.row())
				#remove lspl in data
				self.lspl.Remove(index_data)
				for i in xrange (self.dialog.peak_model.rowCount()):
					item_ = self.dialog.peak_model.item(i, 0)
					item_data = item_.data(Qt.DisplayRole).toString()
					if index_data == item_data:
						index_ = self.dialog.peak_model.indexFromItem(item_)
						self.dialog.peak_model.removeRow(index_.row())
						self.dialog.treeView_2.rowsRemoved(index_, index.row(), index.row())
						
				for i in xrange (self.dialog.clust_model.rowCount()):
					item_ = self.dialog.clust_model.item(i, 0)
					item_data = item_.data(Qt.DisplayRole).toString()
					if index_data == item_data:
						index_ = self.dialog.clust_model.indexFromItem(item_)
						self.dialog.clust_model.removeRow(index_.row())
						self.dialog.treeView_3.rowsRemoved(index_, index.row(), index.row())
			else:
				self.dialog.ShowErrorMessage("Error Blue Screen", "Can not delete one line: index is not valid")
		
		for index in self.dialog.treeView_2.selectedIndexes():	
			if index.isValid():
					#print "remove root..."
					#i.e we are on one root of the tree name file
				value = self.dialog.ShowWarningMessage("Remove Data", "Remove selected Index will lead to the loss of information")
				if value == QtGui.QMessageBox.Cancel:
					return
				index_data = self.dialog.chrom_model.data(index, Qt.DisplayRole).toString()
				#remove the row in the model
				self.dialog.peak_model.removeRow(index.row())
				self.dialog.peak_model.removeRow(index.row())
				#update the view
				self.dialog.treeView_2.rowsRemoved(index, index.row(), index.row())
				#remove lspl in data
				self.lspl.Sample(index_data).set_peak_list(obj.RawPeakList())
				
				for i in xrange (self.dialog.clust_model.rowCount()):
					item_ = self.dialog.clust_model.item(i, 0)
					item_data = item_.data(Qt.DisplayRole).toString()
					if index_data == item_data:
						index_ = self.dialog.clust_model.indexFromItem(item_)
						self.dialog.clust_model.removeRow(index_.row())
						self.dialog.treeView_3.rowsRemoved(index_, index.row(), index.row())
						
		for index in self.dialog.treeView_3.selectedIndexes():	
			if index.isValid():
				value = self.dialog.ShowWarningMessage("Remove Data", "Remove selected Index will lead to the loss of information")
				if value == QtGui.QMessageBox.Cancel:
					return
				index_data = self.dialog.clust_model.data(index, Qt.DisplayRole).toString()
				#remove the row in the model
				self.dialog.clust_model.removeRow(index.row())
				self.dialog.clust_model.removeRow(index.row())
				#update the view
				self.dialog.treeView_3.rowsRemoved(index, index.row(), index.row())
				for peak in self.lspl.Sample(index_data).get_peak_list():
					peak.set_frag_cluster(obj.ClusterList())
